# 报废系统
from django import forms
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.forms.models import model_to_dict
from web.models import Scrap, Product, Users, ScrapImage
from web.apis import tools
from django.db.models import Q
import uuid
import os
# 报废表单
class ScrapForm(forms.ModelForm):
    class Meta:
        model = Scrap
        fields = ['scrap_product', 'scrap_location', 'scrap_number', 'scrap_reason', 'scrap_user']
        exclude = ['scrap_id', 'create_time', 'update_time']

    def clean_scrap_number(self):
        scrap_number = self.cleaned_data.get('scrap_number')
        if scrap_number <= 0:
            raise forms.ValidationError("报废数量必须大于0")
        return scrap_number

    def clean_scrap_reason(self):
        scrap_reason = self.cleaned_data.get('scrap_reason')
        if not scrap_reason:
            raise forms.ValidationError("报废原因不能为空")
        if len(scrap_reason) > 200:
            raise forms.ValidationError("报废原因不能超过200个字符")
        return scrap_reason

    def clean_scrap_location(self):
        scrap_location = self.cleaned_data.get('scrap_location')
        if scrap_location not in [1, 2]:
            raise forms.ValidationError("报废位置格式不正确")
        return scrap_location

# 创建报废记录
@csrf_exempt
def create_scrap(request):
    if request.method == 'POST':
        form = ScrapForm(request.POST)
        if form.is_valid():
            try:
                # 检查商品库存
                product = Product.objects.filter(product_id=form.cleaned_data['scrap_product']).first()
                if product and product.stock < form.cleaned_data['scrap_number']:
                    return JsonResponse(tools.ReturnData(code=400, msg='商品库存不足'))
                
                # 检查货架/仓库库存
                if form.cleaned_data['scrap_location'] == 1:  # 货架
                    if product and product.shelf_number < form.cleaned_data['scrap_number']:
                        return JsonResponse(tools.ReturnData(code=400, msg='货架库存不足'))
                else:  # 仓库
                    if product and product.warehouse_number < form.cleaned_data['scrap_number']:
                        return JsonResponse(tools.ReturnData(code=400, msg='仓库库存不足'))
                
                # 创建报废记录
                scrap = form.save(commit=False)
                scrap.scrap_id = str(uuid.uuid4())  # 手动设置 scrap_id
                scrap.save()
                
                scrap_dict = model_to_dict(scrap)
                scrap_dict['create_time'] = scrap.create_time.strftime('%Y-%m-%d %H:%M:%S')
                scrap_dict['update_time'] = scrap.update_time.strftime('%Y-%m-%d %H:%M:%S')
                
                # 获取商品信息
                if scrap.scrap_product:
                    product = Product.objects.filter(id=scrap.scrap_product.id).first()
                    if product:
                        scrap_dict['product'] = model_to_dict(product)
                
                # 获取操作员信息
                if scrap.scrap_user:
                    user = Users.objects.filter(id=scrap.scrap_user.id).first()
                    if user:
                        scrap_dict['user'] = model_to_dict(user)
                        del scrap_dict['user']['password']
                        scrap_dict['user']['create_time'] = user.create_time.strftime('%Y-%m-%d %H:%M:%S')
                        scrap_dict['user']['update_time'] = user.update_time.strftime('%Y-%m-%d %H:%M:%S')
                        scrap_dict['user']['avatar'] = user.avatar.url if user.avatar else None
                
                # 获取报废图片
                images = ScrapImage.objects.filter(scrap=scrap)
                image_list = []
                for image in images:
                    image_dict = {
                        'id': image.id,
                        'image': image.image.url if image.image else None,
                        'create_time': image.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                        'update_time': image.update_time.strftime('%Y-%m-%d %H:%M:%S')
                    }
                    image_list.append(image_dict)
                scrap_dict['images'] = image_list
                
                return JsonResponse(tools.ReturnData(code=200, msg='创建报废记录成功', data=scrap_dict))
            except Exception as e:
                return JsonResponse(tools.ReturnData(code=400, msg=f'创建报废记录失败: {str(e)}'))
        else:
            print(form.errors)
            error_msg = tools.get_first_error(form)
            return JsonResponse(tools.ReturnData(code=400, msg=f' {error_msg}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用POST方法'))

# 获取报废记录列表
@csrf_exempt
def get_scrap_list(request):
    if request.method == 'GET':
        try:
            scraps = Scrap.objects.all().order_by('-create_time')
            scrap_list = []
            for scrap in scraps:
                scrap_dict = model_to_dict(scrap)
                scrap_dict['create_time'] = scrap.create_time.strftime('%Y-%m-%d %H:%M:%S')
                scrap_dict['update_time'] = scrap.update_time.strftime('%Y-%m-%d %H:%M:%S')
                
                # 获取商品信息
                if scrap.scrap_product:
                    product = Product.objects.filter(id=scrap.scrap_product.id).first()
                    if product:
                        scrap_dict['product'] = model_to_dict(product)
                
                # 获取操作员信息
                if scrap.scrap_user:
                    user = Users.objects.filter(id=scrap.scrap_user.id).first()
                    if user:
                        scrap_dict['user'] = model_to_dict(user)
                        del scrap_dict['user']['password']
                        scrap_dict['user']['create_time'] = user.create_time.strftime('%Y-%m-%d %H:%M:%S')
                        scrap_dict['user']['update_time'] = user.update_time.strftime('%Y-%m-%d %H:%M:%S')
                        scrap_dict['user']['avatar'] = user.avatar.url if user.avatar else None
                # 获取报废图片
                images = ScrapImage.objects.filter(scrap=scrap)
                image_list = []
                for image in images:
                    image_dict = {
                        'id': image.id,
                        'image': image.image.url if image.image else None,
                        'create_time': image.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                        'update_time': image.update_time.strftime('%Y-%m-%d %H:%M:%S')
                    }
                    image_list.append(image_dict)
                scrap_dict['images'] = image_list
                
                scrap_list.append(scrap_dict)
            return JsonResponse(tools.ReturnData(code=200, msg='获取报废记录列表成功', data=scrap_list))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'获取报废记录列表失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用GET方法'))

# 获取单个报废记录
@csrf_exempt
def get_scrap(request, scrap_id):
    if request.method == 'GET':
        try:
            scrap = Scrap.objects.filter(scrap_id=scrap_id).first()
            if not scrap:
                return JsonResponse(tools.ReturnData(code=400, msg='报废记录不存在'))
            
            scrap_dict = model_to_dict(scrap)
            scrap_dict['create_time'] = scrap.create_time.strftime('%Y-%m-%d %H:%M:%S')
            scrap_dict['update_time'] = scrap.update_time.strftime('%Y-%m-%d %H:%M:%S')
            
            # 获取商品信息
            if scrap.scrap_product:
                product = Product.objects.filter(id=scrap.scrap_product.id).first()
                if product:
                    scrap_dict['product'] = model_to_dict(product)
            
            # 获取操作员信息
            if scrap.scrap_user:
                user = Users.objects.filter(id=scrap.scrap_user.id).first()
                if user:
                    scrap_dict['user'] = model_to_dict(user)
                    del scrap_dict['user']['password']
                    scrap_dict['user']['create_time'] = user.create_time.strftime('%Y-%m-%d %H:%M:%S')
                    scrap_dict['user']['update_time'] = user.update_time.strftime('%Y-%m-%d %H:%M:%S')
                    scrap_dict['user']['avatar'] = user.avatar.url if user.avatar else None
            
            # 获取报废图片
            images = ScrapImage.objects.filter(scrap=scrap)
            image_list = []
            for image in images:
                image_dict = {
                    'id': image.id,
                    'image': image.image.url if image.image else None,
                    'create_time': image.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                    'update_time': image.update_time.strftime('%Y-%m-%d %H:%M:%S')
                }
                image_list.append(image_dict)
            scrap_dict['images'] = image_list
            
            return JsonResponse(tools.ReturnData(code=200, msg='获取报废记录成功', data=scrap_dict))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'获取报废记录失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用GET方法'))

# 更新报废记录
@csrf_exempt
def update_scrap(request, scrap_id):
    if request.method == 'POST':
        try:
            scrap = Scrap.objects.filter(scrap_id=scrap_id).first()
            if not scrap:
                return JsonResponse(tools.ReturnData(code=400, msg='报废记录不存在'))
            
            form = ScrapForm(request.POST, instance=scrap)
            if form.is_valid():
                # 检查商品库存
                product = Product.objects.filter(product_id=form.cleaned_data['scrap_product']).first()
                quantity_diff = form.cleaned_data['scrap_number'] - scrap.scrap_number
                
                if quantity_diff > 0:  # 如果报废数量增加
                    if product and product.stock < quantity_diff:
                        return JsonResponse(tools.ReturnData(code=400, msg='商品库存不足'))
                    
                    # 检查货架/仓库库存
                    if form.cleaned_data['scrap_location'] == 1:  # 货架
                        if product and product.shelf_number < quantity_diff:
                            return JsonResponse(tools.ReturnData(code=400, msg='货架库存不足'))
                    else:  # 仓库
                        if product and product.warehouse_number < quantity_diff:
                            return JsonResponse(tools.ReturnData(code=400, msg='仓库库存不足'))
                
                # 更新报废记录
                form.save()
                
                scrap_dict = model_to_dict(form.instance)
                scrap_dict['create_time'] = form.instance.create_time.strftime('%Y-%m-%d %H:%M:%S')
                scrap_dict['update_time'] = form.instance.update_time.strftime('%Y-%m-%d %H:%M:%S')
                
                # 获取商品信息
                if form.instance.scrap_product:
                    product = Product.objects.filter(id=form.instance.scrap_product.id).first()
                    if product:
                        scrap_dict['product'] = model_to_dict(product)
                
                # 获取操作员信息
                if form.instance.scrap_user:
                    user = Users.objects.filter(id=form.instance.scrap_user.id).first()
                    if user:
                        scrap_dict['user'] = model_to_dict(user)
                        del scrap_dict['user']['password']
                        scrap_dict['user']['create_time'] = user.create_time.strftime('%Y-%m-%d %H:%M:%S')
                        scrap_dict['user']['update_time'] = user.update_time.strftime('%Y-%m-%d %H:%M:%S')
                        scrap_dict['user']['avatar'] = user.avatar.url if user.avatar else None
                
                # 获取报废图片
                images = ScrapImage.objects.filter(scrap=form.instance)
                image_list = []
                for image in images:
                    image_dict = {
                        'id': image.id,
                        'image': image.image.url if image.image else None,
                        'create_time': image.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                        'update_time': image.update_time.strftime('%Y-%m-%d %H:%M:%S')
                    }
                    image_list.append(image_dict)
                scrap_dict['images'] = image_list
                
                return JsonResponse(tools.ReturnData(code=200, msg='更新报废记录成功', data=scrap_dict))
            else:
                error_msg = tools.get_first_error(form)
                return JsonResponse(tools.ReturnData(code=400, msg=f' {error_msg}'))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'更新报废记录失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用POST方法'))

# 删除报废记录
@csrf_exempt
def delete_scrap(request, scrap_id):
    if request.method == 'DELETE':
        try:
            scrap = Scrap.objects.filter(scrap_id=scrap_id).first()
            if not scrap:
                return JsonResponse(tools.ReturnData(code=400, msg='报废记录不存在'))
            
            # 恢复商品库存
            product = Product.objects.get(id=scrap.scrap_product.id)
            product.stock += scrap.scrap_number
            
            # 恢复货架/仓库库存
            if scrap.scrap_location == 1:  # 货架
                product.shelf_number += scrap.scrap_number
            else:  # 仓库
                product.warehouse_number += scrap.scrap_number
            
            product.save()
            
            # 删除报废记录
            scrap.delete()
            return JsonResponse(tools.ReturnData(code=200, msg='删除报废记录成功'))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'删除报废记录失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用DELETE方法'))

# 搜索报废记录
@csrf_exempt
def search_scrap(request):
    """
    支持的搜索字段:
    商品名称
    商品ID
    操作员名称
    报废原因
    报废ID
    """
    if request.method == 'GET':
        keyword = request.GET.get('keyword', '').strip()
        try:
            query = Q()
            if keyword:
                # 搜索商品名称
                query |= Q(scrap_product__name__icontains=keyword)
                # 搜索商品ID
                query |= Q(scrap_product__product_id__icontains=keyword)
                # 搜索操作员名称
                query |= Q(scrap_user__username__icontains=keyword)
                # 搜索报废原因
                query |= Q(scrap_reason__icontains=keyword)
                # 搜索报废ID
                query |= Q(scrap_id__icontains=keyword)
            
            scraps = Scrap.objects.filter(query).order_by('-create_time')
            scrap_list = []
            for scrap in scraps:
                scrap_dict = model_to_dict(scrap)
                scrap_dict['create_time'] = scrap.create_time.strftime('%Y-%m-%d %H:%M:%S')
                scrap_dict['update_time'] = scrap.update_time.strftime('%Y-%m-%d %H:%M:%S')
                
                # 获取商品信息
                if scrap.scrap_product:
                    product = Product.objects.filter(id=scrap.scrap_product.id).first()
                    if product:
                        scrap_dict['product'] = model_to_dict(product)
                
                # 获取操作员信息
                if scrap.scrap_user:
                    user = Users.objects.filter(id=scrap.scrap_user.id).first()
                    if user:
                        scrap_dict['user'] = model_to_dict(user)
                        del scrap_dict['user']['password']
                        scrap_dict['user']['create_time'] = user.create_time.strftime('%Y-%m-%d %H:%M:%S')
                        scrap_dict['user']['update_time'] = user.update_time.strftime('%Y-%m-%d %H:%M:%S')
                        scrap_dict['user']['avatar'] = user.avatar.url if user.avatar else None
                
                # 获取报废图片
                images = ScrapImage.objects.filter(scrap=scrap)
                image_list = []
                for image in images:
                    image_dict = {
                        'id': image.id,
                        'image': image.image.url if image.image else None,
                        'create_time': image.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                        'update_time': image.update_time.strftime('%Y-%m-%d %H:%M:%S')
                    }
                    image_list.append(image_dict)
                scrap_dict['images'] = image_list
                
                scrap_list.append(scrap_dict)
            return JsonResponse(tools.ReturnData(code=200, msg='搜索报废记录成功', data=scrap_list))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'搜索报废记录失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用GET方法'))

# 上传报废图片
@csrf_exempt
def upload_scrap_image(request, scrap_id):
    if request.method == 'POST':
        try:
            scrap = Scrap.objects.filter(scrap_id=scrap_id).first()
            if not scrap:
                return JsonResponse(tools.ReturnData(code=400, msg='报废记录不存在'))
            
            if 'image' not in request.FILES:
                return JsonResponse(tools.ReturnData(code=400, msg='请上传图片'))
            
            image = ScrapImage.objects.create(
                scrap=scrap,
                image=request.FILES['image']
            )
            
            image_dict = {
                'id': image.id,
                'image': image.image.url if image.image else None,
                'create_time': image.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                'update_time': image.update_time.strftime('%Y-%m-%d %H:%M:%S')
            }
            
            return JsonResponse(tools.ReturnData(code=200, msg='上传报废图片成功', data=image_dict))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'上传报废图片失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用POST方法'))

# 删除报废图片
@csrf_exempt
def delete_scrap_image(request, image_id):
    if request.method == 'DELETE':
        try:
            image = ScrapImage.objects.filter(id=image_id).first()
            if not image:
                return JsonResponse(tools.ReturnData(code=400, msg='报废图片不存在'))
            
            # 删除图片文件
            if image.image:
                if os.path.isfile(image.image.path):
                    os.remove(image.image.path)
            
            # 删除数据库记录
            image.delete()
            return JsonResponse(tools.ReturnData(code=200, msg='删除报废图片成功'))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'删除报废图片失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用DELETE方法'))